/**
 * description：整屏高度计算
 * author：
 * */

/*
* @usage：
*    <div v-adaptive-height="{otherOffset:30,type:'maxHeight',overflow: 'auto'}"></div>
*       @params:
*           type:设置的属性类型。maxHeight/height。默认为maxHeight。
*           otherOffset：待减的其他高度
*           overflow: 需要滚动的类型  默认为auto
*  */
import Vue from 'vue';
import {on, off} from './lib/dom';
/* 转为驼峰 */
const toHump = (str) => {
    if (typeof str !== 'string') return '';
    return str.replace(/-(\w)/, ($0, $1) => {
        return $1.toUpperCase();
    });
};
function computedHeightFn(el, binding, vnode) {
    Vue.nextTick(() => {
        /* 支持的type类型 */
        let allowTypeArr = ['height', 'maxHeight'];
        let otherOffset = binding.value ? (binding.value.otherOffset || 0) : 20;
        /* type类型处理 */
        let typeProperty = binding.value && toHump(binding.value.type);
        let prop = typeProperty && allowTypeArr.includes(typeProperty) ? typeProperty : 'maxHeight';
        /* 获取使用指令的组件实例，如果使用指令的不是组件，则为undefined */
        let {componentInstance: $table} = vnode;
        let computedHeight = window.innerHeight - el.getBoundingClientRect().top - otherOffset;
        if ($table && $table.layout) {
            /* 设置el-table高度：
                        set body height and set fixed body height,and set table height by setHeight()
                */
            Vue.nextTick(() => {
                $table.layout[`set${prop.replace(/\w/, $0 => $0.toUpperCase())}`](computedHeight);
                let {headerHeight} = $table.layout, fixedDOM = $table.$el.querySelector('.el-table__fixed-body-wrapper');
                $table.$el.querySelector('.el-table__body-wrapper').style[prop] = `${computedHeight - headerHeight}px`;
                if (fixedDOM)fixedDOM.style[prop] = `${computedHeight - headerHeight}px`;
            });
            //  设置table高度
            if (binding.value.func) {
                binding.value.func(computedHeight);
            }
        } else {
            Vue.nextTick(() => {
                computedHeight = window.innerHeight - el.getBoundingClientRect().top - otherOffset;
                el.style[prop] = `${ computedHeight}px`;
                el.style['overflow'] = binding.value.overflow ? binding.value.overflow : 'auto';

            });

        }
    });
}

export default {
    bind(el, binding, vnode) {
        el.resizeHandler = () => {
            computedHeightFn(el, binding, vnode);
        };
        on(window, 'resize', el.resizeHandler);
    },
    inserted(el, binding, vnode) {
        computedHeightFn(el, binding, vnode);
    },
    unbind(el) {
        off(window, 'resize', el.resizeHandler);
    }
};
